package com.yupi.springbootinit.bimq;

import com.yupi.springbootinit.constant.MqConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Configuration
public class BiMqInit {

    /**
     * 声明普通队列和交换机
     *
     * @return
     */
    @Bean("bi_exchange")
    public DirectExchange biExchange(){
        return new DirectExchange(MqConstant.EXCHANGE_NAME);
    }

    @Bean("bi_queue")
    public Queue biQueue(){
        HashMap<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", MqConstant.DEAD_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", MqConstant.DEAD_ROUTING_KEY);
        args.put("x-message-ttl", 180000);
        return new Queue(MqConstant.QUEUE_NAME, true, false, false, args);
    }

    @Bean
    public Binding bindBiQueue(@Qualifier("bi_exchange") DirectExchange biExchange, @Qualifier("bi_queue") Queue biQueue){
        return BindingBuilder.bind(biQueue).to(biExchange).with(MqConstant.ROUTING_KEY);
    }

    /**
     * 声明死信交换机和死信队列
     * */
    @Bean("dead_exchange")
    public DirectExchange deadExchange(){
        return new DirectExchange(MqConstant.DEAD_EXCHANGE_NAME);
    }

    @Bean("dead_queue")
    public Queue deadQueue(){
        return new Queue(MqConstant.DEAD_QUEUE_NAME, true);
    }

    @Bean
    public Binding bingDeadQueue(@Qualifier("dead_exchange") DirectExchange deadExchange, @Qualifier("dead_queue") Queue deadQueue){
        return BindingBuilder.bind(deadQueue).to(deadExchange).with(MqConstant.DEAD_ROUTING_KEY);
    }

    /**
     * 声明保证 redis 和 mysql 双写一致性的队列
     * */
    @Bean("redis_mysql_consist_queue")
    public Queue redisMySQLConsistQueue(){
        return new Queue(MqConstant.REDIS_MYSQL_CONSIST_QUEUE_NAME, true);
    }

    @Bean
    public Binding bindRedisMySQLConsistQueue(@Qualifier("bi_exchange") DirectExchange biExchange, @Qualifier("redis_mysql_consist_queue") Queue redisMysqlConsistQueue){
        return BindingBuilder.bind(redisMysqlConsistQueue).to(biExchange).with(MqConstant.REDIS_MYSQL_CONSIST_ROUTING_KEY);
    }

}
